from collections import OrderedDict

from apps.goods.models import GoodsChannel, GoodsCategory


def get_categories():
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # 2定义一个字典，组合返回的数据格式    # OrderedDict会根据key自动排序
    categories = OrderedDict()

    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {"channels": [], "sub_cats": []}

        category1 = channel.category

        categories[group_id]["channels"].append({
            "id": category1.id,
            "name": category1.name,
            "url": channel.url
        })

        category2s = category1.subs.all()

        for category2 in category2s:
            category3s = category2.subs.all()

            categories[group_id]["sub_cats"].append({
                "id": category2.id,
                "name": category2.name,
                "sub_cats": [{"id": cat3.id, "name": cat3.name} for cat3 in category3s]
            })

    return categories


'''面包屑'''

def get_breadcrumb(category: GoodsCategory):
    ret = {

    }
    if category.parent is None:
        ret["cat1"] = category.name
    elif category.parent.parent is None:
        ret["cat1"] = category.parent.name
        ret["cat2"] = category.name
    else:
        ret["cat1"] = category.parent.parent.name
        ret["cat2"] = category.parent.name
        ret["cat3"] = category.name

    return ret
